package com.test.mall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.test.common.constant.AuthServerConstant;
import com.test.common.utils.HttpUtils;
import com.test.common.utils.R;
import com.test.mall.auth.feign.MemberFeignService;
import com.test.common.vo.MemberRespVo;
import com.test.mall.auth.vo.SocialUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * 处理社交登录请求
 */
@Slf4j
@Controller
public class OAuth2Controller {

    @Autowired
    MemberFeignService memberFeignService;

    @GetMapping("/oauth2.0/gitee/success")
    public String gitee(@RequestParam("code") String code, HttpSession session) throws Exception {
        Map<String, String> map = new HashMap<>();
        map.put("client_id","bec1dd7a4f5073b90531d086b0fbecbb47bee28a20273abe1eacecc48b246a59");
        map.put("client_secret","33405de7085d860a378e26d31b1ff9d9e9eb332abe9a01c0c17019f7e5525a6d");
        map.put("grant_type","authorization_code");
        map.put("redirect_uri","http://localhost:20000/oauth2.0/gitee/success");
        map.put("code",code);
        //根据code换取accessToken
        HttpResponse response = HttpUtils.doPost("https://gitee.com", "/oauth/token", "post", new HashMap<>(), null, map);
        //处理
        if(response.getStatusLine().getStatusCode()==200){
            //获取到了accessToken
            String json = EntityUtils.toString(response.getEntity());
            SocialUser socialUser = JSON.parseObject(json, SocialUser.class);
            R oauthLogin = memberFeignService.oauthLogin(socialUser);
            if (oauthLogin.getCode()==0){
                MemberRespVo data = oauthLogin.getData("data", new TypeReference<MemberRespVo>() {});
                log.info("成功登录："+data.toString());
                session.setAttribute(AuthServerConstant.LOGIN_USER,data);
                //登录成功就跳回首页
                return "redirect:http://testmall.com";
            } else {
                return "redirect:http://auth.testmall.com/login.html";
            }
        } else {
            return "redirect:http://auth.testmall.com/login.html";
        }
    }

}
